
package com.bdtop.dbl.ui.activities.device;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UpdateNicknameActivity
 * @Description: TODO
 * @author: liyongqiang
 * @date:2014-10-23
 */
public class DeviceModiPhonesActivity extends BaseActivity {

    private Button btnAddNewPhone;
//    private Button btnConfirm;

    // public static final String EXTRA_PHONES = "extra_phones";

    private String[] sosPhones;

    private ListView listView;
    private PhonesAdapter adapter;
    private List<String> mDataList = new ArrayList<String>();

    public static final int ADD_NEW_PHONE = -1;

    private DeviceInfo device;

    public static final void launch(Context context, DeviceInfo device) {
        Intent intent = new Intent(context, DeviceModiPhonesActivity.class);
        intent.putExtra(Constants.INTENT_DEVICE, device);
        context.startActivity(intent);
    }

    private void modiSosPhones() {
        showWaitingFlag();
//        btnConfirm.setVisibility(View.GONE);

        final String[] phones = new String[mDataList.size()];
        for (int i = 0; i < mDataList.size(); i++) {
            phones[i] = mDataList.get(i);
        }
        String sign = Preferences.getLoginSign(this);
        String mdn = "";
        if(device != null){
        	mdn = device.mdn;
        }
        ServerApiFactory.getApiImpl().deviceModi(sign, mdn, null, null, null, phones,
                new RequestCallback() {
                    @Override
                    public void onSuccess(String rawData, Object response) {
                        hiddenWaitingFlag();

                        BaseResponse br = (BaseResponse) response;
                        showToast(br.getDesc());
                        if (br.getStatus().equals(Constants.REQUEST_SUCCESS)) {
//                        	btnConfirm.setVisibility(View.GONE);
                        	if(DBLApplication.getInstance().deviceInfoList !=null && device !=null){
	                            for (DeviceInfo d : DBLApplication.getInstance().deviceInfoList) {
	                                if (d.mdn.equals(device.mdn)) {
	                                    d.sos_phones = phones;
	                                    break;
	                                }
	                            }
                        	}
                        }
                    }

                    @Override
                    public void onError(int statusCode, Throwable e, String rawData) {
                        // dismissDialog();
                        hiddenWaitingFlag();
//                        btnConfirm.setVisibility(View.VISIBLE);
                        if (NetworkUtils.isNetConnect(getApplicationContext())) {
                            showToast(R.string.oper_error);
                        } else {
                            showToast(R.string.net_error);
                        }
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_modi_device_phones);
        super.onCreate(savedInstanceState);

        device = (DeviceInfo) getIntent().getSerializableExtra(Constants.INTENT_DEVICE);
        if(DBLApplication.getInstance().deviceInfoList != null && device != null ){
	        for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
	            if (di.mdn.equals(device.mdn)) {
	                device = di;
	                break;
	            }
	        }
        }
        if(device != null){
        	sosPhones = device.sos_phones;	
        }
        // getIntent().getStringArrayExtra(EXTRA_PHONES);
        if (sosPhones != null && sosPhones.length > 0) {
            for (int i = 0; i < sosPhones.length; i++) {
                mDataList.add(sosPhones[i]);
            }
        }

        mTitleBar.setTitle(R.string.modify_info_item_4_1);
        initMenus();

        btnAddNewPhone = (Button) findViewById(R.id.btn_add);
        btnAddNewPhone.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (mDataList.size() < 5) {
                    showModiDialog(ADD_NEW_PHONE);
                } else {
                    showToast(R.string.max_phone_count);
                }
            }
        });
        listView = (ListView) findViewById(R.id.listview);
        adapter = new PhonesAdapter();
        listView.setAdapter(adapter);
    }

    private void initMenus() {
//        btnConfirm = new Button(DeviceModiPhonesActivity.this);
//        btnConfirm.setText(R.string.confirm);
//        btnConfirm.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
//                LayoutParams.MATCH_PARENT));
//        btnConfirm.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
//        btnConfirm.setTextColor(Color.WHITE);
//        btnConfirm.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View arg0) {
//                modiSosPhones();
//            }
//        });
//        mTitleBar.addMenu(btnConfirm);
    }

    class PhonesAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mDataList != null)
                return mDataList.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (mDataList != null && mDataList.size() > 0)
                return mDataList.get(position);
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {
            String phone = mDataList.get(position);
            ViewCache mViewCache;
            if (view == null) {
                mViewCache = new ViewCache();
                view = LayoutInflater.from(DeviceModiPhonesActivity.this)
                        .inflate(R.layout.listitem_phones, null);
                // init view
                mViewCache.txPhone = (TextView) view.findViewById(R.id.tx_phone);
                view.setTag(mViewCache);
            } else {
                mViewCache = (ViewCache) view.getTag();
            }
            // set data
            mViewCache.txPhone.setText(phone);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    showManageDialog(position, view);
                }
            });

            return view;
        }

        class ViewCache {
            TextView txPhone;
        }
    }

    private Dialog manageDialog;

    private void showManageDialog(final int index, View parent) {
        View content = LayoutInflater.from(this).inflate(R.layout.dialog_select_2_2, null);
        content.findViewById(R.id.tx_del).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mDataList.remove(index);
                adapter.notifyDataSetChanged();
                modiSosPhones();
                dismissManageDialog();
            }
        });

        content.findViewById(R.id.tx_modify).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                showModiDialog(index);
                dismissManageDialog();
            }
        });

        manageDialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);

        manageDialog.setContentView(content);
        manageDialog.setCanceledOnTouchOutside(true);
        manageDialog.setCancelable(true);
        manageDialog.show();
    }

    private void dismissManageDialog() {
        if (manageDialog != null && manageDialog.isShowing())
            manageDialog.dismiss();
        manageDialog = null;
    }

    private Dialog modiDialog;

    private void showModiDialog(final int index) {
        View content = LayoutInflater.from(this).inflate(R.layout.dialog_modi3_number, null);

        TextView txTitle = (TextView) content.findViewById(R.id.tx_title);
        if (index == ADD_NEW_PHONE) {
            txTitle.setText(R.string.add);
        } else {
            txTitle.setText(R.string.modify);
        }

        final EditText edText = (EditText) content.findViewById(R.id.ed_text);
        edText.setHint(R.string.hint_modi_phones);
        // InputFilter[] filters = {
        // new LengthFilter(11)
        // };
        // edText.setFilters(filters);
        content.findViewById(R.id.btn_ok).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String value = edText.getText().toString().trim();
                if (TextUtils.isEmpty(value)) {
                    showToast(R.string.mobile_format_2);
                } else if (value.length() != 11) {
                    showToast(R.string.mobile_format);
                } else {
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).equals(value)) {
                            showToast(R.string.had_add_mun);
                            return;
                        }
                    }

                    if (index == ADD_NEW_PHONE) {
                        mDataList.add(edText.getText().toString());
                        adapter.notifyDataSetChanged();
                        modiSosPhones();
                    } else {
                        mDataList.set(index, edText.getText().toString());
                        adapter.notifyDataSetChanged();
                        modiSosPhones();
                    }
                    dismissModiDialog();
                }
            }
        });

        modiDialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);

        modiDialog.setContentView(content);
        modiDialog.setCanceledOnTouchOutside(true);
        modiDialog.setCancelable(true);
        modiDialog.show();
    }

    private void dismissModiDialog() {
        if (modiDialog != null && modiDialog.isShowing())
            modiDialog.dismiss();
        modiDialog = null;
    }

}
